import { Button, Modal, Tooltip, Space, Typography, Tag, Spin } from "antd";
import { CopyOutlined, CheckOutlined, FileTextOutlined, LoadingOutlined } from "@ant-design/icons";
import { useState, useRef, useEffect } from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism";

const { Text, Title } = Typography;

const NacosYamlModal = (props) => {
    const { yamlConfigDetailParam, setYamlConfigDetailParam, yamlContent, isLoading = false } = props;
    const [copied, setCopied] = useState(false);
    const codeRef = useRef(null);
    const modalRef = useRef(null);

    // 复制YAML内容到剪贴板
    const copyToClipboard = () => {
        if (!yamlContent) return;

        navigator.clipboard.writeText(yamlContent).then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }).catch(() => {
            // 降级方案：使用textarea复制
            const textarea = document.createElement('textarea');
            textarea.value = yamlContent;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        });
    };

    // 关闭模态框
    const handleClose = () => {
        setYamlConfigDetailParam(prev => ({
            ...prev,
            visible: false
        }));
    };

    // 刷新内容（如果需要）
    const handleRefresh = () => {
        props.onRefresh?.();
    };

    // 组件卸载时重置状态
    useEffect(() => {
        return () => {
            setCopied(false);
        };
    }, []);

    return (
        <Modal
            ref={modalRef}
            title={
                <div style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    width: "100%",
                    padding: "4px 0"
                }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                        <FileTextOutlined style={{ color: "#165DFF", fontSize: 18 }} />
                        <Title level={5} style={{
                            margin: 0,
                            color: "#1d2129",
                            fontWeight: 600
                        }}>
                            {yamlConfigDetailParam?.yamlDataId || "配置详情"}
                        </Title>
                        <Tag
                            color="#165DFF"
                            size="small"
                            style={{
                                backgroundColor: "#e8f3ff",
                                color: "#165DFF",
                                borderColor: "#bfdbfe"
                            }}
                        >
                            YAML 配置
                        </Tag>
                    </div>

                    <Space size="small">
                        {props.onRefresh && (
                            <Tooltip title="刷新配置内容">
                                <Button
                                    icon={<LoadingOutlined style={{ fontSize: 14 }} />}
                                    size="small"
                                    onClick={handleRefresh}
                                    loading={isLoading}
                                    style={{
                                        backgroundColor: "#f0f2f5",
                                        border: "none",
                                        transition: "all 0.2s"
                                    }}
                                    hoverStyle={{ backgroundColor: "#e5e6eb" }}
                                />
                            </Tooltip>
                        )}
                        <Tooltip title={copied ? "已复制成功" : "复制配置内容"}>
                            <Button
                                icon={copied ? <CheckOutlined style={{ color: "#52c41a" }} /> : <CopyOutlined />}
                                size="small"
                                onClick={copyToClipboard}
                                disabled={!yamlContent || isLoading}
                                style={{
                                    backgroundColor: copied ? "#f6ffed" : "#f0f2f5",
                                    color: copied ? "#52c41a" : "inherit",
                                    border: "none",
                                    transition: "all 0.2s",
                                    marginRight: '24px'
                                }}
                                hoverStyle={{ backgroundColor: copied ? "#eaffd0" : "#e5e6eb" }}
                            />
                        </Tooltip>
                    </Space>
                </div>
            }
            open={!!yamlConfigDetailParam?.visible}
            width={document.documentElement.clientWidth > 1200 ? "80%" : "90%"}
            onCancel={handleClose}
            footer={[
                <Button
                    danger={true}
                    key="close"
                    onClick={handleClose}
                    style={{
                        transition: "all 0.2s",
                        borderRadius: 6,
                        padding: "6px 16px"
                    }}
                    hoverStyle={{ transform: "translateY(-2px)", boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)" }}
                >
                    关闭
                </Button>,
            ]}
            destroyOnClose={true}
            maskClosable={false}
            style={{ borderRadius: "12px" }}
            bodyStyle={{
                padding: 0,
                overflow: "hidden",
                backgroundColor: "#fafafa",
                borderTop: "1px solid #f0f0f0"
            }}
            modalRender={(node) => (
                <div style={{
                    borderRadius: "12px",
                    overflow: "hidden",
                    boxShadow: "0 10px 30px -5px rgba(0, 0, 0, 0.1)",
                    border: "1px solid #e5e7eb"
                }}>
                    {node}
                </div>
            )}
        >
            {/* YAML内容展示区域 */}
            <div style={{
                position: "relative",
                maxHeight: "70vh",
                overflow: "hidden"
            }}>
                {/* 加载状态覆盖层 */}
                {isLoading && (
                    <div style={{
                        position: "absolute",
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        backgroundColor: "rgba(0, 0, 0, 0.5)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        zIndex: 10,
                        backdropFilter: "blur(2px)"
                    }}>
                        <Spin
                            size="large"
                            tip="加载配置中..."
                            style={{ color: "#fff" }}
                        />
                    </div>
                )}

                <div style={{
                    height: "70vh",
                    overflowY: "auto",
                    overflowX: "auto",
                    padding: "1px",
                    backgroundColor: "#282c34"
                }}>
                    {yamlContent ? (
                        <SyntaxHighlighter
                            ref={codeRef}
                            language="yaml"
                            style={dracula}
                            showLineNumbers={true}
                            lineNumberStyle={{
                                color: "#636d83",
                                borderRight: "1px solid #4b5263",
                                paddingRight: "12px",
                                paddingLeft: "8px",
                                marginRight: "16px",
                                userSelect: "none",
                                fontSize: "13px"
                            }}
                            wrapLines={false}
                            customStyle={{
                                margin: 0,
                                padding: "24px 16px",
                                borderRadius: 0,
                                fontSize: "14px",
                                lineHeight: "1.7",
                                whiteSpace: "pre",
                                minHeight: "100%"
                            }}
                        >
                            {yamlContent}
                        </SyntaxHighlighter>
                    ) : (
                        <div style={{
                            textAlign: "center",
                            color: "#ff9a9e",
                            padding: "60px 20px",
                            minHeight: "70vh",
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            justifyContent: "center",
                            gap: 16,
                            backgroundColor: "#282c34"
                        }}>
                            <FileTextOutlined style={{ fontSize: 48, color: "#4c516d" }} />
                            <Text style={{ fontSize: 16 }}>暂无配置内容</Text>
                            {props.onRefresh && (
                                <Button
                                    icon={<LoadingOutlined />}
                                    onClick={handleRefresh}
                                    size="small"
                                    style={{
                                        marginTop: 8,
                                        backgroundColor: "#4c516d",
                                        borderColor: "#4c516d",
                                        color: "#fff"
                                    }}
                                >
                                    重试加载
                                </Button>
                            )}
                        </div>
                    )}
                </div>

                {/* 底部信息栏 */}
                {yamlContent && (
                    <div style={{
                        padding: "8px 16px",
                        backgroundColor: "#1e2128",
                        borderTop: "1px solid #4b5263",
                        fontSize: "12px",
                        color: "#8a919f",
                        display: "flex",
                        justifyContent: "space-between"
                    }}>
                        <Text>语法高亮已启用 · YAML 格式</Text>
                        <Text>
                            {yamlContent.split('\n').length} 行 · 约 {Math.ceil((yamlContent.length / 1024) * 10) / 10} KB
                        </Text>
                    </div>
                )}
            </div>
        </Modal>
    );
};

export default NacosYamlModal;